/**
 * <p>formpanel的控制类</p>
 * 继承自Ext.app.Controller

 * @module Ext-ux-cceaf-controller
 * @class cceaf.controller.FormPanelCtrl
 * @extends Ext.app.Controller
 * @since 1.0
 */
Ext.define('cceaf.controller.FormPanelCtrl',{
	extend: 'Ext.app.Controller', 
	requires: [
	    
    ],
	
    constructor: function(config){
		config = config || {};
		
		config = Ext.applyIf(config || {}, {

		});

		cceaf.controller.FormPanelCtrl.superclass.constructor.apply(this, arguments);
	},

	/**
     * 监听事件
     */
    init: function() {
    	//控制层需控制视图的xtype
    	var controlledViewXType = this.controlledViewXType;
    	if (!controlledViewXType) {
    		//控制名称
    		var className = this.self.getName();
    		alert('必须设置控制层' + className + '需控制视图的xtype，即controlledViewXType属性！');
    		return;
    	}
    	
    	//构建初始化的事件监听
    	var eventTemplate = "this.control({" + 
	    	"'aaaaa': {" +
	    	"	afterrender: this.initPage" +
	        "}," +
        	"'aaaaa #btnSave': {" + 
            "    click: this.page_save" + 
            "}," + 
            "'aaaaa #btnClose': {" + 
            "    click: this.page_close" + 
            "}" + 
    	"});";
	    
	    var eventString = eventTemplate.replace(/aaaaa/gi, controlledViewXType);
	    eval(eventString);
        
        this.registerEvent();
        
      //标记已经初始化完成
        this.isInit = true;
    },
    
    /**
     * 对于动态加载controller模式
     * 第一次加载后设置为true，再次加载后不在执行init方法 
     * 
     * @property isInit 
     * @type Boolean
     * @default false
     */
    isInit: false,
    
    /**
     * 监听其他事件
     */
    registerEvent: function(){
    	
    },
    
    /**
	 * 关闭弹出页面
	 *
     * @method page_close 
     */
    page_close: function(){
    	var billForm = this.getControlledView();
    	var addAndEditWin = billForm.up('window');
    	if (addAndEditWin) {
    		addAndEditWin.close();
    	}
    },
    
    /**
	 * 获取视图
	 *
     * @return {Ext.container.Container} 视图对象
     */
    getControlledView: function(){
    	var controlledViewXType = this.controlledViewXType;
    	var methodName = 'this.get' + controlledViewXType.substr(0,1).toUpperCase() + controlledViewXType.substring(1) + '()';
    	//alert(methodName);
    	
    	var view = eval(methodName);
    	return view;
    },
    
    /**
     * 进入页面时，设置初始值
     */
    initPage: function(){
    	
    },
    
    /**
     * 校验表单数据的有效性，如果要校验需在子类加载
     *
     * @return {Boolean} 校验成功范围true
     */
    checkForm: function(){
    	return true;
    },
    
    /**
     * 表单载入数据后,设置特殊值表单值
     */
    initEditPage: function(){
    	
    },
    
    /**
     * 保存后的回调函数
     */
    saveCallback: function(){
    	
    },
    
    /**
     * 保存对象
     */
     page_save: function(){
    	 var billForm = this.getControlledView();
    	 if (!billForm.saveAction) {
    		 alert('表单的saveAction没有设置！');
    		 return;
    	 }
    	 
     	 var submitParam = {
     		 formSubmit: true, //form提交
     		 actionURL: billForm.saveAction,
 			 closePopWin: true,  //保存数据后关闭窗口
 			 formLoad: false //提交数据后不加载form的数据
     	 };
 		
 		 this.page_submit(submitParam, this.saveCallback);
     },
     
    /**
     * 提交页面
     * <br>示例： submitParam = { <br>
     * <br>	formSubmit: true, //false为ajax提交，true为form.submit <br>
     * <br>    actionURL： '',	//提交的action <br>
     * <br>    closePopWin: true, //保存数据后关闭窗口
     * <br>    params: {}, //提交的参数,json表达 <br>
     * <br>    formLoad: false, //提交数据后重新载入数据 <br>
     * <br> } 
     *
     * @method page_submit
     * @param {attribute} submitParam 提交参数 
     * @param {fn} callback 提交完成后调用的回调函数
     */
     page_submit: function(submitParam, callback){
    	 var controller = this;
    	 var billForm = controller.getControlledView();
     	
		var formSubmit = true;
		var closePopWin = true;
		var formLoad = false;
		var actionURL;
		var params = {};

     	if (submitParam) {
     		if ( Ext.isDefined( submitParam.formSubmit )) {
     			formSubmit = submitParam.formSubmit;
     		}
     		if ( Ext.isDefined( submitParam.actionURL )) {
     			actionURL = submitParam.actionURL;
     		}
     		if ( Ext.isDefined( submitParam.closePopWin )) {
    			closePopWin = submitParam.closePopWin;
    		}
     		if ( Ext.isDefined( submitParam.params )) {
     			params = submitParam.params;
     		}
     		if ( Ext.isDefined( submitParam.formLoad )) {
     			formLoad = submitParam.formLoad;
     		}
     	}
     	
     	if (!actionURL) {
     		cceaf.util.ExtHelper.showInfoDialog("action 没有定义！");
     		return; 
     	}
 		
     	if(!billForm.form.isValid()){
 			return;
 		}
     	if(!controller.checkForm()){
     		return;
     	}

 		//组装主表 JSONString
 		var masterJSONData = new Object();
 		var formFields = billForm.query('.field');
 		
 		for(var i=0; formFields != null && i<formFields.length; i++){
     		var item = formFields[i];
     		var itemId = item.getName(); //注意:此处最好用getName,而不用getId
 			var itemValue = item.getValue();
 			
 			if(Ext.isDate(itemValue)){
 				itemValue = Ext.Date.format(itemValue,'Y-m-d');
 			}
 			
 			if (item.getXType() != 'filefield') {
 				var splitIndex = itemId.indexOf("-");
 				if( splitIndex > 0) {
 					cceaf.util.ExtHelper.showInfoDialog('必须设置' + itemId.substr(itemId, splitIndex) + '字段的name属性！');
 					return;
 				}
 				eval("masterJSONData." + itemId + " = '" + itemValue + "'");
 			}
     	}
 		
     	var masterJSONString = Ext.JSON.encode(masterJSONData);
       	//alert(masterJSONString);
       	
 		params.masterJSONString = masterJSONString;
 		
 		if (formSubmit) {
 	     	billForm.form.submit({
 	        	url:  actionURL,
 	        	params: params,
 	        	waitMsg : '正在保存数据...',
 	            success: function(from, action) { 
 	            	cceaf.util.ExtHelper.showInfoDialog(action.result.message); 
 	            	
 	            	if ( formLoad ) {
 	            		controller.page_load(action);
 	            	}
 	            	
 	            	if (callback) {
 	            		callback();
 	            	}
 	            	
 	            	if ( closePopWin ) {
 	            		controller.page_close();
 	            	}
 	            },
 	            failure: function(from, action) {
 	            	cceaf.util.ExtHelper.processFailureAction(action); 
 	            }
 	        });	
 	     
 	     } else {
 	     	Ext.MessageBox.wait('正在处理数据...', '提示'); //进度条等待
 	      	Ext.Ajax.request({
 	      		url:  actionURL,
 	      		params: params,
 	      		success: function(response){
 	      			var isProcessSucess = cceaf.util.ExtHelper.processAjaxRequest(response,true);
 	      			
 	      			if ( formLoad ) {
 	            		controller.page_load(action);
 	            	}
 	      			
 	      			if (callback) {
 	            		callback();
 	            	}
 	            	
 	            	if ( closePopWin ) {
 	            		controller.page_close();
 	            	}
 	   			},
 	   			failure: function(response){
 	   				cceaf.util.ExtHelper.processAjaxRequest(response,false);
 	   			}
 	      	});
 	     }
 	     
     },
     
     /**
      * 页面提交成功后的数据重新载入，主要可以加载服务端生成的数据，如自增长的主键
      * 
      * @param {Ext.form.action.Action} action 
      */
     page_load: function(action){
    	 var controller = this;
    	 var billForm = controller.getControlledView();
 
    	 var masterkeys;
    	 if (!billForm.masterKeyIds) {
    		 alert('请设置表单的masterKeyIds！');
    		 return;
    	 } 
    	 masterkeys = billForm.masterKeyIds.split(',');
    	 
    	 var url;
    	 if (!billForm.findByKeyAction) {
    		 alert('请设置表单的findByKeyAction！');
    		 return;
    	 } 
    	 url = billForm.findByKeyAction + '?';
     	
     	
     	for(var i=0;i<masterkeys.length;i++){
 			var temp = eval("action.result." + masterkeys[i]);
 			if (!temp) {
 				alert('执行saveAction后没有从服务端返回对象的主键' + masterkeys[i] + '的值！');
 				break;
 			}
 			url += masterkeys[i] + '=' + temp + '&';
 		}
 		billForm.form.reset();
 		
     	//装载对象到表单
     	billForm.form.load({
 	        waitMsg : '正在载入数据...',
 	        url:  url,
     		success: function(form,action) { 
 	        	//表单载入数据时,设置特殊值
     			controller.initEditPage(action);
     			
 	        	//显示正确提示
 	        	var jsonObject =eval("(" + action.response.responseText + ")");
 	        	cceaf.util.ExtHelper.showInfoDialog(jsonObject.message);
 	        },
 	        failure: function(form,action) {
 	        	//显示错误提示
 	        	var jsonObject =eval("(" + action.response.responseText + ")");
 	        	cceaf.util.ExtHelper.showErrorDialog(jsonObject.message);
 	        }
 	   	});
     },
     
     /**
      * 根据页面上对象主键加载页面数据
      *
      * @param {Array} masterKeyValues 主键数组
      */
     form_load: function(masterKeyValues){
    	var controller = this;
    	var billForm = controller.getControlledView();
     	
     	var masterkeys = billForm.masterKeyIds.split(',');
     	var url = billForm.findByKeyAction + '?';
     	for(var i=0;i<masterkeys.length;i++){
     		var keyValue;
     		if (masterKeyValues) {
     			keyValue = masterKeyValues[i];
     		} else {
     			keyValue = billForm.down('[name=' + masterkeys[i] + ']').getValue();
     		}
     		
 			url += masterkeys[i] + '=' + keyValue + '&';
 		}
 		billForm.form.reset();

     	//装载对象到表单
     	billForm.form.load({
 	        waitMsg : '正在载入数据...',
 	        url: url,
     		success: function(form,action) { 
 	        	//表单载入数据时,设置特殊值,包括载入细表数据
     			controller.initEditPage(action);
     			
 	        	//显示正确提示
 	        	var jsonObject =eval("(" + action.response.responseText + ")");
 	        	cceaf.util.ExtHelper.showInfoDialog(jsonObject.message);
 	        },
 	        failure: function(form,action) {
 	        	//显示错误提示
 	        	var jsonObject =eval("(" + action.response.responseText + ")");
 	        	cceaf.util.ExtHelper.showErrorDialog(jsonObject.message);
 	        }
 	   	});
     }
    
});